import { defineStore } from "pinia";
import { api_get_all_city, api_get_user_address } from "@/service/api/address";
import { format_address } from "@/utils/format-user-address";

export const use_order_store = defineStore("order_store", {
  state: (): any => {
    //   生成订单所需要的数据
    return {
      goods_info: [],
      addr_id: "",
      address_info: "",
      shoppingCartIds: [],
      selected_cart_item: [],

      // 存放用户的的地址
      user_address: null,
      // 存放用户的订单信息
      user_order: [],
      page_scene: 0,
      city_list: null,
      formated_order_address: null,
    };
  },
  actions: {
    create_new_order(): any {
      this.selected_cart_item.forEach((item) => {
        this.goods_info.push({
          id: item.goods_id,
          num: item.num,
        });
        this.shoppingCartIds.push(item.id);
      });
      return {
        goods_info: this.goods_info,
        addr_id: this.addr_id,
        shoppingCartIds: this.shoppingCartIds,
        selected_cart_item: this.selected_cart_item,
      };
    },

    // 在仓库里可以发请求获取全部用户地址
    async get_user_address() {
      let res: any = await api_get_user_address();
      this.user_address = res.result;
      console.log(res);
    },

    // 调用获取全部的城市列表
    async get_all_city() {
      let res: any = await api_get_all_city();
      this.city_list = res.result;
    },
    // 调用它传入已经生成的订单的id,获取格式化后的数据
    async format_user_address() {
      // 调用这个要发两个请求,一个是发请求获取城市列表,一个是获取用户的地址
      await this.get_user_address();
      await this.get_all_city();

      const order_address = this.user_address.filter((address) => {
        return address.id == this.user_order.addr_id;
      });
      let map_array = order_address.map((address: any) => {
        return {
          id: address.id,
          name: address.name,
          tel: address.phone,
          address: `${format_address(address.area, this.city_list)} ${
            address.desc
          }`,
        };
      });
      this.formated_order_address = map_array[0];
    },
  },

  persist: true,
});
